package net.lab1024.sa.base.kafka;

import cn.idev.excel.util.DateUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.domain.EventBaseAlert;
import net.lab1024.sa.base.common.domain.EventResult;
import net.lab1024.sa.base.common.domain.SoarResult;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.module.support.soaraction.domain.entity.SoarActionEntity;
import net.lab1024.sa.base.module.support.soaraction.domain.form.SoarActionAddForm;
import net.lab1024.sa.base.module.support.soaraction.service.SoarActionService;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

// DataConsumer.java
@Component
@Slf4j
public class DataConsumer {

    @Autowired
    private SoarActionService soarActionService;

    @KafkaListener(
            topics = "alert-soar-event",
            groupId = "keji-soc-web",
            properties = {
                    "auto.offset.reset=latest"  // 关键配置
            }
    )
    public void consume(String massage) {
        try {
            EventBaseAlert alert = JSONObject.parseObject(massage, EventBaseAlert.class);
            SoarActionAddForm from = new SoarActionAddForm();
            from.setEsid(alert.getEsId());
            from.setEventName(alert.getEventName());
            from.setEventId(alert.getEventId());
            from.setCreateTime(DateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            from.setAction("未处置");
            from.setSrcIp(alert.getSrcIp());
            from.setDstIp(alert.getDstIp());
            soarActionService.add(from);
        } catch (Exception e) {
            log.error("获取推送记录 consume kafka message error, message: {}", massage, e);
        }

    }


    @KafkaListener(
            topics = "soc_event_alert_result",
            groupId = "keji-soc-web",
            properties = {
                    "auto.offset.reset=latest"  // 关键配置
            }
    )
    public void resultconsume(String massage) {
        try {
            SoarResult alert = JSONObject.parseObject(massage, SoarResult.class);
            List<EventResult> eventList = alert.getEventList();
            for (EventResult eventResult : eventList) {
                SoarActionAddForm from = new SoarActionAddForm();
                from.setEventId(eventResult.getEventId());
                from.setAction(alert.getStatus());
                soarActionService.updateByEsid(from);
            }

        } catch (Exception e) {
            log.error("修改记录 consume kafka message error, message: {}", massage, e);
        }

    }
}